package wang.conge.javasedemo.core.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
 * @author conge
 * 2016年7月14日
 */
public class AsynchronousIOClient implements Runnable{
	private static Charset charset = Charset.forName("UTF-8");

	private String name;
	private String ip;
	private int port;
	
	public AsynchronousIOClient(String index,String ip,int port){
		this.name  = index;
		this.ip = ip;
		this.port = port;
	}
	
	@Override
	public void run() {
		try {
			AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
			Future<Void> future = client.connect(new InetSocketAddress(ip, port));
			future.get();
			
			ByteBuffer buffer = ByteBuffer.wrap((name + "hello").getBytes());
			Future<Integer> fut = client.write(buffer);
			fut.get();
			
			doRead(client);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("close client");
			System.exit(0);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	private static void doRead(AsynchronousSocketChannel client){
		ByteBuffer dst = ByteBuffer.allocate(1024);
		Future<Integer> fut = client.read(dst);	
		
		try {
			fut.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		dst.flip();
		String res = charset.decode(dst).toString();
		
		System.out.println(res);
	}
	
	public static void main(String[] args) {
		String ip = "127.0.0.1";
		int port = 10000;
		
		for(int i=0;i<10;i++){
			String name = "client:"+i;
			
			new Thread(new AsynchronousIOClient(name,ip,port)).start();
		}
		
	}
}
